/*
	This file is part of Lproxy.

    Lproxy is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    Lproxy is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with Lproxy.  If not, see <http://www.gnu.org/licenses/>.
*/
package lproxy_client;

import java.io.*;
import java.net.*;
import java.nio.ByteBuffer;
import java.util.*;
import java.util.Map.Entry;

class ConnectServer extends Connection
{
	public ConnectServer(String p_url,ConnectClient p_cc) throws Exception
	{
		this.m_cc = p_cc;
		this.m_connection = (HttpURLConnection)new URL(p_url).openConnection();
		this.m_connection.setRequestProperty("User-Agent","Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)");
		this.m_connection.setRequestMethod("POST");
		this.m_connection.setDoOutput(true);
		this.m_connection.setConnectTimeout(this.TIME_OUT * 1000);
	}
	public void Send(String p_data) throws Exception
	{
		this.m_out = this.m_connection.getOutputStream();
		OutputStreamWriter output = new OutputStreamWriter(this.m_out);
		
		Map<String,String> header = ParseHeader(p_data);
		String post_to_server = new String("");
		post_to_server += "LENGTH=" + LCoder.encode(this.LENGTH) + "&";
		post_to_server += "BEGIN_SIGN=" + LCoder.encode(this.BEGIN_SIGN) + "&";
		post_to_server += "END_SIGN=" + LCoder.encode(this.END_SIGN) + "&";
		post_to_server += "TIME_OUT=" + LCoder.encode(String.valueOf(this.TIME_OUT)) + "&";
		post_to_server += "address=" + LCoder.encode(header.get("address")) + "&";
		header.remove("address");
		post_to_server += "port=" + LCoder.encode(header.get("port")) + "&";
		header.remove("port");
		
		String content = header.get("content");
		header.remove("content");

		String post_content = new String("");
		post_content += header.get("method");
		header.remove("method");
		post_content += " ";
		post_content += header.get("path");
		header.remove("path");
		post_content += " ";
		post_content += header.get("protocol");
		header.remove("protocol");
		post_content += CRLF;

		Iterator<Entry<String,String>> i = header.entrySet().iterator();
		while(i.hasNext())
		{
			Entry<String,String> b = i.next();
			post_content += b.getKey() + ": " + b.getValue() + CRLF;
		}
		post_content += CRLF;
		if((content != null) && (content.equals("") == false))
		{
			post_content += content;
		}
		post_to_server += "data=" + LCoder.encode(post_content);
		output.write(post_to_server);
		output.flush();
	}
	public void ReceiveAndSend() throws Exception
	{
		this.m_in = this.m_connection.getInputStream();
		String buffer = new String();
		byte[] receive_buffer = new byte[this.MAX_BUFFER_SIZE];
		int len = 0;
		while(true)
		{
			if((len = this.m_in.read(receive_buffer,0,this.MAX_BUFFER_SIZE)) == -1)
				break;
			buffer += new String(receive_buffer,0,len);
			
			List<String> receive_data = new LinkedList<String>();
			int receive_length = 0;
			while(buffer.indexOf(this.BEGIN_SIGN) != -1 && buffer.indexOf(this.END_SIGN) != -1)
			{
				int begin,end;
				begin = buffer.indexOf(this.BEGIN_SIGN);
				end = buffer.indexOf(this.END_SIGN);
				String temp = buffer.substring(begin + this.BEGIN_SIGN.length(),end);
				receive_data.add(temp);
				receive_length += temp.length();
				buffer = buffer.substring(end + this.END_SIGN.length());
			}
			if(receive_length <= 0)
				continue;
			if(receive_data.isEmpty())
				continue;
			ByteBuffer send_data = ByteBuffer.allocate(receive_length/4*3);
			for(String temp:receive_data)
			{
				send_data.put(LCoder.decode(temp));
			}
			receive_data.clear();
			this.m_cc.Send(send_data.array());
		}
	}
	private final String BEGIN_SIGN = "-B-";
	private final String END_SIGN = "-E-";
	private final String LENGTH = "24";
	private HttpURLConnection m_connection;
	private ConnectClient m_cc;
}
